import json
from datetime import datetime
import os

def sync_skill_data():
    # --------------------------
    # 1. 读取源文件 skill_names.json
    # --------------------------
    source_path = 'skill_names.json'
    try:
        with open(source_path, 'r', encoding='utf-8') as f:
            source_data = json.load(f)
    except FileNotFoundError:
        print(f"错误：未找到 {source_path} 文件,将创建新文件")
        source_data = {"skill_names": {}, "last_updated": ""}
    except json.JSONDecodeError:
        print(f"错误：{source_path} 格式不正确,将创建新文件")
        source_data = {"skill_names": {}, "last_updated": ""}

    # --------------------------
    # 2. 处理并生成 skill_names_v2.json（带ID排序）
    # --------------------------
    v2_path = 'skill_names_v2.json'
    # 初始化v2数据（若存在则读取,否则新建）
    v2_data = {"skill_names": {}, "last_updated": ""}
    if os.path.exists(v2_path):
        try:
            with open(v2_path, 'r', encoding='utf-8') as f:
                v2_data = json.load(f)
        except json.JSONDecodeError:
            print(f"警告：{v2_path} 格式错误,将重新创建")

    source_skills = source_data["skill_names"]
    v2_skills = v2_data["skill_names"]

    # 处理v2数据（核心逻辑：新增ID/更新名称变更）
    for skill_id, skill_name in source_skills.items():
        if skill_id not in v2_skills:
            # 新增ID：添加name和默认type
            v2_skills[skill_id] = {"name": skill_name, "type": "damage"}
        else:
            # 已有ID：检查名称是否变更
            current_name = v2_skills[skill_id]["name"]
            if skill_name != current_name:
                # 初始化name_list（首次变更时加入原名称）
                if "name_list" not in v2_skills[skill_id]:
                    v2_skills[skill_id]["name_list"] = [current_name]
                # 避免重复添加
                if skill_name not in v2_skills[skill_id]["name_list"]:
                    v2_skills[skill_id]["name_list"].append(skill_name)
                # 更新为最新名称
                v2_skills[skill_id]["name"] = skill_name

    # 对v2的skill_names按ID排序（关键新增逻辑）
    def sort_key(skill_id):
        # 尝试将ID转换为数字排序，失败则按字符串排序
        try:
            return int(skill_id)  # 数字ID按数值大小排序
        except ValueError:
            return skill_id  # 非数字ID按字符串字典序排序

    # 按排序后的ID重新构建v2_skills字典
    sorted_v2_skills = {
        sid: v2_skills[sid] 
        for sid in sorted(v2_skills.keys(), key=sort_key)
    }
    v2_data["skill_names"] = sorted_v2_skills

    # 更新v2的最后修改时间（北京时间）
    beijing_time = datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S")
    v2_data["last_updated"] = beijing_time

    # 保存v2文件
    try:
        with open(v2_path, 'w', encoding='utf-8') as f:
            json.dump(v2_data, f, ensure_ascii=False, indent=4)
        print(f"处理完成,已更新 {v2_path}（ID已排序）")
    except IOError:
        print(f"错误：无法写入 {v2_path},请检查权限")
        return

    # --------------------------
    # 3. 同步更新 skill_names.json（补充缺失ID）
    # --------------------------
    # 提取v2中存在但source中不存在的ID
    missing_ids = [sid for sid in v2_skills if sid not in source_skills]
    if missing_ids:
        print(f"发现 {len(missing_ids)} 个缺失ID,正在补充到 {source_path}...")
        for sid in missing_ids:
            # 用v2中的最新名称补充到source
            source_skills[sid] = v2_skills[sid]["name"]
        # 对source的skill_names也按相同规则排序（可选，保持一致性）
        sorted_source_skills = {
            sid: source_skills[sid]
            for sid in sorted(source_skills.keys(), key=sort_key)
        }
        source_data["skill_names"] = sorted_source_skills
        
        # 更新source的最后修改时间（沿用v2的时间,确保一致性）
        source_data["last_updated"] = beijing_time
        # 保存source文件
        try:
            with open(source_path, 'w', encoding='utf-8') as f:
                json.dump(source_data, f, ensure_ascii=False, indent=4)
            print(f"已完成 {source_path} 的缺失ID补充（ID已排序）")
        except IOError:
            print(f"错误：无法写入 {source_path},补充失败")
    else:
        print(f"{source_path} 已包含所有ID,无需补充")

if __name__ == "__main__":
    sync_skill_data()